# coding=utf-8
def main():
	proxies = {'http':'http://127.0.0.1:8000'}
	import urllib
	opener = urllib.URLopener(proxies)
	r = opener.open('http://kohsamui:thailand@www.pythonchallenge.com/pc/rock/mandelbrot.gif')
	import Image, cStringIO
	ufos = Image.open(cStringIO.StringIO(r.read()))
	def mandelbrot(left=0.34, bottom=0.57,width=0.036, height=0.027, max=128, size=(640, 480)):
		xstep = width / size[0]
		ystep = height / size[1]
		for y in xrange(size[1] - 1, -1, -1):
			for x in xrange(size[0]):
				c = complex(left + x * xstep, bottom + y * ystep)
				z = 0 + 0j
				for i in xrange(max):
					z = z * z + c
					if abs(z) > 2:
						break
				yield i
				
	mandel = ufos.copy() # We can reuse the type, size and palette
	mandel.putdata(list(mandelbrot()))
	# mandel.show()

	differences = [(a-b) for a, b in zip(ufos.getdata(), mandel.getdata()) if a != b]
	print len(differences)	# 1679
	print set(differences)	# set([-16, 16])
	
	def factor(n):
		d = 2
		factors = []
		while not n % d:
			factors.append(d)
			n /= d
		d = 3
		while n > 1 and d * d <= n:
			if not n % d:
				factors.append(d)
				n /= d
			else:
				d += 2
		if n > 1:
			factors.append(n)
		return factors	
	print factor(len(differences))
	# [23, 73]

	plot = Image.new('L', (23, 73))
	plot.putdata([(i < 16) and 255 or 0 for i in differences])
	plot.resize((230, 730)).show()
	# Would this be a message from the stars? If it reminds you of the Voyager (http://en.wikipedia.org/wiki/Voyager_Golden_Record) and Pioneer (http://en.wikipedia.org/wiki/Pioneer_plaque) spacecrafts, you wouldn't be too far off. It is, in fact, the message sent by humanity to the stars through the Arecibo telescope (http://en.wikipedia.org/wiki/Arecibo_message). arecibo is the key to the next level. We found the message as it was sent to the stars by the telescope, as a stream of binary information meant for alien consumption. 
	# 下一关：http://www.pythonchallenge.com/pc/rock/arecibo.html

if __name__ == '__main__':
	main()
